package org.example2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFolderByDeepSeek {

    public static void zipFolder(String sourceFolderPath, String zipFilePath) throws IOException {
        File sourceFolder = new File(sourceFolderPath);
        if (!sourceFolder.exists() || !sourceFolder.isDirectory()) {
            throw new IOException("源文件夹不存在或不是一个目录: " + sourceFolderPath);
        }

        try (FileOutputStream fos = new FileOutputStream(zipFilePath);
             ZipOutputStream zos = new ZipOutputStream(fos)) {

            addFolderToZip(sourceFolder, sourceFolder.getName(), zos);
        }
    }

    private static void addFolderToZip(File folder, String parentPath, ZipOutputStream zos) throws IOException {
        File[] files = folder.listFiles();
        if (files == null) {
            throw new IOException("无法访问目录中的文件: " + folder.getAbsolutePath());
        }

        for (File file : files) {
            String entryName = parentPath + "/" + file.getName();
            if (file.isDirectory()) {
                // 递归处理子目录
                addFolderToZip(file, entryName, zos);
                // 添加空目录条目
                if (file.list().length == 0) {
                    zos.putNextEntry(new ZipEntry(entryName + "/"));
                    zos.closeEntry();
                }
            } else {
                // 添加文件条目
                try (FileInputStream fis = new FileInputStream(file)) {
                    ZipEntry zipEntry = new ZipEntry(entryName);
                    zos.putNextEntry(zipEntry);
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = fis.read(buffer)) > 0) {
                        zos.write(buffer, 0, length);
                    }
                }
                zos.closeEntry();
            }
        }
    }

    public static void main(String[] args) {
        try {
            zipFolder("E:\\API\\Java", "F:\\mylib\\file\\output.zip");
            System.out.println("文件夹压缩成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}